package com.dfrz.problem.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dfrz.problem.dao.EmployeeDao;
import com.dfrz.problem.dao.SysAdminDao;
import com.dfrz.problem.model.Employee;
import com.dfrz.problem.model.SysAdmin;
import com.dfrz.problem.model.User;
import com.dfrz.problem.service.LoginService;
import com.dfrz.problem.utils.IConstant;
import com.dfrz.problem.utils.MD5Util;
import com.dfrz.problem.utils.Result;

public class LoginServiceImpl implements LoginService {
	private static final Logger logger = LoggerFactory
			.getLogger(LoginServiceImpl.class);

	private SysAdminDao sysAdminDao;
	private EmployeeDao employeeDao;

	public void setSysAdminDao(SysAdminDao sysAdminDao) {
		this.sysAdminDao = sysAdminDao;
	}
	
	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

	@Override
	public Result<Object> checkLogin(User user) {
		Result<Object> result = new Result<Object>();
		if (user.getLoginType() == 0) {
			// 系统管理员登录
			SysAdmin sysAdmin = sysAdminDao.getSysAdmin(user.getEmail());

			if (sysAdmin != null) {
				// 验证密码是否正确
				if (MD5Util.getMD5Str(user.getPassword()).equalsIgnoreCase(
						sysAdmin.getPassword())) {
					logger.debug("SysAdmin login success,email is : "
							+ sysAdmin.getAdminEmail());
					
					user.setUserName(sysAdmin.getAdminName());
					result.setCode(IConstant.LOGIN_SUCCESS);
					result.setResult(sysAdmin);
				} else {
					result.setCode(IConstant.PASSWORD_ERROR);
				}

			} else {
				// 用户不存在
				result.setCode(IConstant.USER_NOT_EXIST);
			}
		}else{
			// 员工登录
			Employee employee = employeeDao.getEmployee(user.getEmail());
			
			if (employee != null) {
				// 验证密码是否正确
				if (MD5Util.getMD5Str(user.getPassword()).equalsIgnoreCase(
						employee.getPassword())) {
					logger.debug("Employee login success,email is : "
							+ employee.getEmployeeEmail());
					
					user.setUserName(employee.getEmployeeName());
					result.setCode(IConstant.LOGIN_SUCCESS);
					result.setResult(employee);
				} else {
					result.setCode(IConstant.PASSWORD_ERROR);
				}

			} else {
				// 用户不存在
				result.setCode(IConstant.USER_NOT_EXIST);
			}
		}

		return result;
	}

}
